package com.gba.mark.user.service.permission.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.gba.mark.group.entity.Group;
import com.gba.mark.group.service.IGroupService;
import com.gba.mark.user.auth.utils.AuthUtils;
import com.gba.mark.user.entity.permission.UserRole;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gba.mark.user.entity.user.User;
import com.gba.mark.user.mapper.permission.UserRoleMapper;
import com.gba.mark.user.service.permission.IUserRoleService;

import com.gba.mark.user.service.user.IUserService;
import com.gba.mark.user.service.user.impl.UserServiceImpl;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;


    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IUserService userService;

//    @Override
//    public boolean save(Integer userId, Integer roleId) {
//        UserRole sysUserRole = new UserRole();
//        sysUserRole.setUserId(userId);
//        sysUserRole.setRoleId(roleId);
//        userRoleMapper.insert(sysUserRole);
//        return true;
//    }

    //添加组成员功能
    @Override
    public Boolean saveUserRole(Integer userId, Integer groupId) {

        if ((userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("id", userId))) == null) {
            return false;
         // 成员是否已在组内
        }else if (this.baseMapper.selectOne(new QueryWrapper<UserRole>()
                .eq("group_id",groupId)
                .eq("user_id", userId)) != null) {
            return  false;
         //判断是否满员
        } else if (this.userRoleService.listUserRole(groupId).size() ==
                groupService.getOne(new QueryWrapper<Group>().eq("id",groupId)).getSize()) {

            return false;
        } else {
            //添加组员id，角色id，组id
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(3);
            userRole.setGroupId(groupId);
            return userRoleService.save(userRole);
        }
    }


    // 根据用户_id删除用户
    @Override
    public Boolean removeUserRole(Integer userId,Integer groupId){
        return userRoleService.remove(new QueryWrapper<UserRole>()
                .eq("user_id", userId)
                .eq("group_id", groupId));
    }

    //查找组成员信息
    public List<UserRole> listUserRole(Integer groupId) {
        return this.baseMapper.selectList(new QueryWrapper<UserRole>().eq("group_id", groupId));
    }

}
